package com.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.entity.Asset;
import com.project.entity.AssetDepreciation;
import com.project.entity.AssetFix;
import com.project.entity.AssetType;
import com.project.service.AssetDepreciationService;
import com.project.service.AssetFixService;
import com.project.service.AssetService;
import com.project.service.AssetTypeService;
import com.project.util.DateCalculation;
import com.project.util.DateUtil;
import com.project.util.PageBeans;
import com.project.util.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * 资产设备折旧controller
 *
 * @author Leo高洋
 * @create 2023-04-23 11:12
 */
@RestController
@RequestMapping("/assetDepreciation")
public class AssetDepreciationController {
    @Autowired
    private AssetService assetService;

    @Autowired
    private AssetDepreciationService assetDepreciationService;

    @Autowired
    private AssetFixService assetFixService;

    @Autowired
    private AssetTypeService assetTypeService;

    private final static Logger logger = LoggerFactory.getLogger(AssetDepreciationController.class);

    /**
     * 动态多条件分页查询资产设备折旧信息
     *
     * @param pageBeans
     * @return
     */
    @PostMapping("/list")
    public R list(@RequestBody PageBeans pageBeans) {
        logger.info("动态多条件分页查询资产设备折旧信息");
        Map<String, Object> map = pageBeans.getMap();
        map.put("start", pageBeans.getStart());
        map.put("pageSize", pageBeans.getPageSize());
        List<AssetDepreciation> assetDepreciationList = assetDepreciationService.list(map);
        for (AssetDepreciation assetDepreciation : assetDepreciationList) {
            Integer id = assetDepreciation.getTypeid();
            AssetType assetType = assetTypeService.findById(String.valueOf(id));
            assetDepreciation.setAssetType(assetType);
        }
        long total = assetDepreciationService.getTotal(map);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("assetDepreciationList", assetDepreciationList);
        resultMap.put("total", total);
        return R.ok(resultMap);
    }


    /**
     * 保存并计算资产折旧信息
     *
     * @author Leo高洋
     * @create 2023-04-18 13:16
     */
    @PostMapping("/save")
    public R save(@RequestBody AssetDepreciation assetDepreciation) throws ParseException {
        if (assetDepreciation.getId() == null || assetDepreciation.getId() == -1) {
            logger.info("保存资产设备折旧信息");
            assetDepreciation.setZjsj(new Date());// 资产设备折旧时间
            BigDecimal yuanzhi = assetDepreciation.getYuanzhi();// 资产设备的账面价值（资产金额）
            BigDecimal canzhi = BigDecimal.valueOf(yuanzhi.doubleValue() * 0.05);// 资产设备残值
            BigDecimal jinzhi = BigDecimal.valueOf(yuanzhi.doubleValue() - canzhi.doubleValue());// 资产设备净值
            // 计算使用月数
            int month = DateCalculation.monthsBetween(DateUtil.formatDate(assetDepreciation.getRksj()), DateUtil.getCurrentDateFormatter());
            System.out.println("使用的月数是：" + month);
            assetDepreciation.setJingzhi(jinzhi);// 保存净值
            assetDepreciation.setCanzhi(canzhi);// 保存残值
            assetDepreciation.setCanzhilv(BigDecimal.valueOf(0.05));// 保存残值率
            // 按照平均年限法计算
            if (assetDepreciation.getZjff().equals("平均年限法")) {
                // 计算当月折旧
                BigDecimal dyzj =
                        BigDecimal.valueOf(jinzhi.doubleValue() / assetDepreciation.getZjnx() / 12);
                // 计算累计折旧
                BigDecimal zjje = BigDecimal.valueOf(dyzj.doubleValue() * month);
                assetDepreciation.setDyzj(dyzj);
                assetDepreciation.setZjje(zjje);
            }
            // 按照年数总和法计算
            else if (assetDepreciation.getZjff().equals("年数总和法")) {
                int zjnx = assetDepreciation.getZjnx();// 折旧年限
                int yearNum = 0;// 使用年数总和
                for (int i = 1; i <= zjnx; i++) {
                    yearNum += i;
                }
                System.out.println("年数总和是：" + yearNum);
                // 计算已使用的年数
                int yearUsed = DateCalculation.yearsBetween(DateUtil.formatDate(assetDepreciation.getRksj()), DateUtil.getCurrentDateFormatter());
                System.out.println("使用的年数是：" + yearUsed);
                // 计算累计折旧
                int zjje = 0;
                for (int i = 1; i <= yearUsed; i++) {
                    zjje += jinzhi.doubleValue() * yearUsed / yearNum;
                }
                System.out.println("累计折旧是：" + zjje);
                assetDepreciation.setZjje(BigDecimal.valueOf(zjje));
            }
            AssetFix assetFix = assetFixService.getOne(new QueryWrapper<AssetFix>().eq("assetId", assetDepreciation.getAssetid()));
            if (assetFix != null && assetFix.getIsScrapped() == 2) {
                assetDepreciation.setShsj(assetFix.getTbrq());
            }
            assetDepreciationService.saveOrUpdate(assetDepreciation);
            return R.ok("折旧成功");
        } else {
            System.out.println("修改");
            return R.ok();
        }
    }

    /**
     * 根据id查询折旧信息集合
     */
    @PostMapping("listById")
    public R ListById(@RequestBody Integer[] ids) {
        logger.info("根据id查询折旧信息集合");
        List<AssetDepreciation> assetDepList = new ArrayList<>();
        Map<String, Object> resultMap = new HashMap<>();
        for (Integer id : ids) {
            AssetDepreciation assetDep = assetDepreciationService.getById(id);
            assetDepList.add(assetDep);
        }
        resultMap.put("assetDepList", assetDepList);
        return R.ok(resultMap);
    }

    /**
     * 查寻全部折旧信息
     */
    @GetMapping("/listAll")
    public R assetListAll() {
        logger.info("查寻全部折旧信息");
        List<AssetDepreciation> assetDepAllList = assetDepreciationService.list();
        for (AssetDepreciation assetDep : assetDepAllList) {
            Asset asset = assetService.getById(assetDep.getAssetid());
            AssetType assetType = assetTypeService.getById(asset.getTypeId());
            assetDep.setAssetType(assetType);
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("assetDepAllList", assetDepAllList);
        return R.ok(resultMap);
    }
}
